# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-05 23:43
# File     : config.py
# Project  : codebuddy_craft
# Desc     :
# backend/core/config.py
"""
配置加载工具 🔧

提供配置加载和验证功能
"""

import os
import logging
from pathlib import Path
from typing import Any, Dict, Optional

from .settings import Settings, get_settings_by_environment


def load_config(config_file: Optional[str] = None) -> Settings:
    """加载配置文件 📝"""

    # 确定配置文件路径
    if config_file:
        config_path = Path(config_file)
    else:
        # 按优先级查找配置文件
        possible_paths = [
            Path(".env"),
            Path("config/.env"),
            Path("../config/.env"),
        ]

        config_path = None
        for path in possible_paths:
            if path.exists():
                config_path = path
                break

    # 设置环境变量
    if config_path and config_path.exists():
        from dotenv import load_dotenv
        load_dotenv(config_path)
        print(f"✅ 已加载配置文件: {config_path}")
    else:
        print("⚠️ 未找到配置文件，使用默认配置")

    # 根据环境获取设置
    environment = os.getenv("ENVIRONMENT", "development")
    settings = get_settings_by_environment(environment)

    # 验证关键配置
    validate_config(settings)

    return settings


def validate_config(settings: Settings) -> None:
    """验证配置有效性 ✅"""

    errors = []

    # 验证数据库配置
    if not settings.DATABASE_URL:
        errors.append("DATABASE_URL 不能为空")

    # 验证密钥配置
    if len(settings.SECRET_KEY) < 32:
        errors.append("SECRET_KEY 长度至少需要32个字符")

    # 验证邮件配置（如果启用）
    if settings.ENABLE_EMAIL_VERIFICATION:
        if not settings.SMTP_HOST:
            errors.append("启用邮箱验证时，SMTP_HOST 不能为空")
        if not settings.SMTP_USERNAME:
            errors.append("启用邮箱验证时，SMTP_USERNAME 不能为空")

    # 验证AI配置（如果配置了）
    if settings.AI_PROVIDER == "openai" and not settings.AI_API_KEY:
        logging.warning("⚠️ 未配置 OPENAI_API_KEY，AI功能将不可用")

    # 如果有错误，抛出异常
    if errors:
        error_message = "配置验证失败:\n" + "\n".join(f"- {error}" for error in errors)
        raise ValueError(error_message)

    print(f"✅ 配置验证通过 (环境: {settings.ENVIRONMENT})")


def create_directories(settings: Settings) -> None:
    """创建必要的目录 📁"""

    directories = []

    # 上传目录
    if settings.UPLOAD_DIR:
        directories.append(Path(settings.UPLOAD_DIR))

    # 日志目录
    if settings.LOG_FILE:
        log_dir = Path(settings.LOG_FILE).parent
        directories.append(log_dir)

    # 创建目录
    for directory in directories:
        directory.mkdir(parents=True, exist_ok=True)
        print(f"📁 创建目录: {directory}")


def print_config_summary(settings: Settings) -> None:
    """打印配置摘要 📋"""

    print("\n" + "=" * 50)
    print(f"🚀 {settings.PROJECT_NAME} v{settings.PROJECT_VERSION}")
    print("=" * 50)
    print(f"环境: {settings.ENVIRONMENT}")
    print(f"调试模式: {settings.DEBUG}")
    print(f"服务器: {settings.HOST}:{settings.PORT}")
    print(f"数据库: {settings.DATABASE_URL}")
    print(f"邮箱验证: {'启用' if settings.ENABLE_EMAIL_VERIFICATION else '禁用'}")
    print(f"速率限制: {'启用' if settings.RATE_LIMIT > 0 else '禁用'}")
    print(f"AI服务: {settings.AI_PROVIDER}")
    print("=" * 50 + "\n")


# 全局配置实例
_settings: Optional[Settings] = None


def get_app_settings() -> Settings:
    """获取应用配置实例 🔧"""
    global _settings

    if _settings is None:
        _settings = load_config()
        create_directories(_settings)

        # 在开发环境下打印配置摘要
        if _settings.is_development:
            print_config_summary(_settings)

    return _settings
